#!/bin/bash
#
# $Id$
#

. $OPENARS_HOME/common/debug.h || exit 1
. $OPENARS_HOME/common/functions.h || exit 1

DEBUG_LEVEL=2

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME
input_dir=$1
repo_dir=/home/admin/repository
agent_conffile="zabbix_agentd.conf"
agent_binfile="zabbix_agentd"

[ -z "$input_dir" ] && { ERR "need parameter \"dirname\""; exit 1; }
[ ! -d "$input_dir" ] && { ERR "not find dir \"$input_dir\""; exit 1; }
[ ! -f "$input_dir/$agent_conffile" ] && { ERR "not find file \"$agent_conffile\""; exit 1; }
[ ! -f "$(ls $repo_dir/zabbix-1.8.*.rpm | tail -1)" ] && { ERR "not find zabbix-1.8 rpm file"; exit 1; }
[ ! -f "$(ls $repo_dir/zabbix-agent-1.8.*.rpm | tail -1)" ] && { ERR "not find zabbix-agent-1.8 rpm file"; exit 1; }

rpm_zabbix=$(basename $(ls $repo_dir/zabbix-1.8.*.rpm | tail -1))
rpm_zabbix_agent=$(basename $(ls $repo_dir/zabbix-agent-1.8.*.rpm | tail -1))


function create_zsetup() {
cat <<'CREATE_EOF'
#!/bin/bash

export PATH=$HOME/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
agent_confdir="/etc/zabbix"
agent_conffile="zabbix_agentd.conf"
rpm_zabbix=$(ls zabbix-1.8.*.rpm)
rpm_zabbix_agent=$(ls zabbix-agent-1.8.*.rpm)

[ -f "$agent_confdir/$agent_conffile" ] && sudo cp $agent_confdir/$agent_conffile $agent_confdir/$agent_conffile.save.`date +%Y%m%d`
sudo rpm -Uv $rpm_zabbix
sudo rpm -Uv $rpm_zabbix_agent
sudo /sbin/chkconfig zabbix-agent on

sudo cp $agent_conffile $agent_confdir/$agent_conffile
if sudo /etc/init.d/zabbix-agent status; then
        sudo /etc/init.d/zabbix-agent restart
else
        sudo /etc/init.d/zabbix-agent start
fi

exit 0

CREATE_EOF
}

zsetup_dir=zagent
mkdir $TEMPDIR/$zsetup_dir
cp $input_dir/$agent_conffile $TEMPDIR/$zsetup_dir || exit 1
cp $repo_dir/$rpm_zabbix $TEMPDIR/$zsetup_dir || exit 1
cp $repo_dir/$rpm_zabbix_agent $TEMPDIR/$zsetup_dir || exit 1

cd $TEMPDIR/$zsetup_dir
create_zsetup >> zsetup.sh
[ $? -ne 0 ] && exit 1
chmod +x zsetup.sh
cd $TEMPDIR 
tar -cf $zsetup_dir.tar $zsetup_dir

host=$(basename $input_dir)
ssh_command="tar -xf $zsetup_dir.tar; cd $zsetup_dir; ./zsetup.sh"

    sftp -o BatchMode=yes $user@$host &> /dev/null << END
put $zsetup_dir.tar
END
    sftp_code=$?
    [ $sftp_code -ne 0 ] && { WARN "Error sftp-connect or sftp-commands on $host: exit_code=$sftp_code"; exit 1; }
    SSH $user@$host "$ssh_command" out_info
	echo "$out_info" > $TEMPDIR/out_info.out
    while read line; do
        INF "$line"
    done < $TEMPDIR/out_info.out    

exit 0 

